package com.dayaokeji.rhythmschoolstudent.client.home.course;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blog.www.guideview.Guide;
import com.common.zxing.CaptureActivity;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.GenerateQRCodeActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.PermissionGuideHelperActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.ShowBigImageActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.VieAnswerActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.common.base.Constant;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.bean.SignQrCodeContent;
import com.dayaokeji.rhythmschoolstudent.client.common.exam.ExamActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.resource.SharedResourceActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.seat.student_seat.StudentSeatActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.vote.VoteActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.adapter.InteractiveAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.adapter.MembersAvatarAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.data.CourseInteractiveData;
import com.dayaokeji.rhythmschoolstudent.client.home.course.ranking.CourseScoringRankingActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.services.CourseScoringService;
import com.dayaokeji.rhythmschoolstudent.client.home.course.task.CourseTaskActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.utils.SignFlag;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.ComponentBean;
import com.dayaokeji.rhythmschoolstudent.client.home.helper.CourseSignFailedHelperActivity;
import com.dayaokeji.rhythmschoolstudent.client.message.GroupsActivity;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.DeleteCourseFinishEvent;
import com.dayaokeji.rhythmschoolstudent.event.UpdateCourseEvent;
import com.dayaokeji.rhythmschoolstudent.glide.GlideUrlModel;
import com.dayaokeji.rhythmschoolstudent.receiver.VieAnswerBean;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.FilenameUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ImageUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ItemDecorationUtil;
import com.dayaokeji.rhythmschoolstudent.utils.MD5Util;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionGroup;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.SignUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.rhythmschoolstudent.utils.WebTimeHandle;
import com.dayaokeji.rhythmschoolstudent.utils.WifiUtil;
import com.dayaokeji.rhythmschoolstudent.view.CourseScoringView;
import com.dayaokeji.rhythmschoolstudent.wiget.CreateLeaveDialog;
import com.dayaokeji.rhythmschoolstudent.wiget.NotPermissionTipsDialog;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.Page;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.CourseApi;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.api.VieAnswerApi;
import com.dayaokeji.server_api.domain.Course;
import com.dayaokeji.server_api.domain.CourseSign;
import com.dayaokeji.server_api.domain.Member;
import com.dayaokeji.server_api.domain.SignResult;
import com.dayaokeji.server_api.domain.UserInfo;
import com.dayaokeji.server_api.domain.VieAnswer;
import com.dayaokeji.server_api.utils.FileFunctionFlag;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import top.zibin.luban.Luban;


/**
 * 课程详情
 */
public class CourseDetailActivity extends BaseActivity {

    public static final String EXTRA_COURSE_ENTITY = "course_entity";

    private static final int SCAN_WIFI_QR_CODE_REQUEST_CODE = 1002;
    private static final int TAKE_SELF_PHOTO_REQUEST_CODE = 1004;
    private static final int LEAVE_IMG_REQUEST_CODE = 1005;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_class_room)
    TextView tvClassRoom;
    @BindView(R.id.tv_teacher_name)
    TextView tvTeacherName;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.btn_sign)
    Button btnSign;
    @BindView(R.id.btn_qr_code_sign)
    Button btnQrCodeSign;
    @BindView(R.id.gv_course_interactive)
    RecyclerView gvCourseInteractive;
    @BindView(R.id.tv_join_code)
    TextView tvJoinCode;
    @BindView(R.id.iv_sign_success)
    ImageView ivSignSuccess;
    @BindView(R.id.tv_members_count)
    TextView tvMembersCount;
    @BindView(R.id.rv_course_members)
    RecyclerView rvCourseMembers;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.course_scoring_view)
    CourseScoringView courseScoringView;

    private ImageView leaveImageView;
    private int leaveImageId = -1;
    private boolean isSaveInstanceState = false;

    private Course course;
    private final List<String> wifiList = new ArrayList<>();
    private final CourseApi courseApi = ApiUtils.getApi(CourseApi.class);
    private final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private final VieAnswerApi vieAnswerApi = ApiUtils.getApi(VieAnswerApi.class);
    private final UserApi userApi = ApiUtils.getApi(UserApi.class);
    private Call<ServerResponse<SignResult>> signCall;
    private Guide guide;
    private AppCompatDialog appCompatDialog;
    private Call<ServerResponse<List<Member>>> studentListCall;
    private Call<ServerResponse<List<Integer>>> uploadCall;
    private static Member member;
    private UserInfo userInfo;
    private ProgressDialog progressDialog;
    private Integer signId = -1;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private boolean isShowSignTime = false;
    private InteractiveAdapter componentAdapter;
    private Call<ServerResponse<Void>> goIntoCall;
    private Call<ServerResponse<Integer>> leaveCall;

    private MembersAvatarAdapter courseMembersAvatarAdapter = new MembersAvatarAdapter();
    private Call<ServerResponse<Page<Course>>> courseDetailCall;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);
        setSupportActionBar(toolbar);
        EventBus.getDefault().register(this);
        course = (Course) getIntent().getSerializableExtra(EXTRA_COURSE_ENTITY);
        if (course == null) {
            ToastUtils.warning(R.string.data_incorrect);
            ActivityStackManager.finish();
            return;
        }
        setInteractive();
        init();
    }

    private void init() {
        setupView();
        initData();
        setOnListener();
        showSignSuccess();
    }

    private void setupView() {
        rvCourseMembers.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        rvCourseMembers.setAdapter(courseMembersAvatarAdapter);
    }

    private void showSignSuccess(){
        if (course != null && ivSignSuccess != null) {
            ivSignSuccess.setVisibility(course.getSignStatus() == 2 ? View.VISIBLE:View.INVISIBLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.course_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item != null) {
            switch (item.getItemId()) {
                case R.id.menu_delete_course:
                    ExitCourseActivity.Companion.navigation(CourseDetailActivity.this, course);
                    break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 更新课程信息
     */
    private void reqCourseDetail() {
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            courseDetailCall = courseApi.findCourseById(1, userInfo.getId(), userInfo.getUniversityId(), course.getCourseDetailId(), 1, 1);
            courseDetailCall.enqueue(new ServerCallback<Page<Course>>() {
                @Override
                public void onResponse(boolean success, ServerResponse<Page<Course>> response) {
                    if (success) {
                        if (response.getBody() != null && !response.getBody().getList().isEmpty()) {
                            CourseDetailActivity.this.course = response.getBody().getList().get(0);;
                            startSign();
                            showSignSuccess();
                            signBtnStatus();
                            final UpdateCourseEvent updateCourseEvent = new UpdateCourseEvent();
                            updateCourseEvent.setCourse(course);
                            EventBus.getDefault().post(updateCourseEvent);
                            if (swipeRefresh != null) {
                                if (swipeRefresh.isRefreshing()) {
                                    swipeRefresh.setRefreshing(false);
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    @SuppressLint("CheckResult")
    private Observable<Integer> checkWebTimeSignStatus() {
        //noinspection unchecked
        return WebTimeHandle.checkSignStatus(course).map(new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer status) throws Exception {
                if (status != null) {
                    switch (status) {
                        case 1:
                            signBtnStatus();
                            break;
                        case 2:
                            if (btnSign != null && btnQrCodeSign != null) {
                                btnSign.setText("未开始签到");
                                btnQrCodeSign.setEnabled(false);
                            }
                            break;
                        case 3:
                            if (btnSign != null && btnQrCodeSign != null) {
                                btnSign.setText(SignUtils.getSignStatus(course.getSignStatus()));
                                btnSign.setEnabled(false);
                                btnQrCodeSign.setEnabled(false);
                            }
                            break;
                    }
                }
                return status;
            }
        });
    }

    @SuppressLint("CheckResult")
    private void startSign() {
        btnSign.setText("检测中....");
        if (course.getSignStatus() != SignFlag.SIGNED && (course.getSignOutStatus() != null && course.getSignOutStatus() == 1)) {
            compositeDisposable.add(checkWebTimeSignStatus().subscribe(new Consumer<Integer>() {
                @Override
                public void accept(Integer status) throws Exception {
                    if (status != null) {
                        if (status == 1 && course.getSignStatus() == SignFlag.NOT_SIGNED || (course.getSignStatus() == 5 && course.getSignType() == 2)) { // 签到
                            validateMacAddress();
                        }else if (status == 2 && course.getSignStatus() == SignFlag.NOT_SIGNED){
                            compositeDisposable.add( WebTimeHandle.getSignDateTime(course).subscribe(new Consumer<String>() {
                                @Override
                                public void accept(String s) throws Exception {
                                    if (!TextUtils.isEmpty(s) && isShowSignTime){
                                        Snackbar.make(getWindow().getDecorView(), "签到将在"+s+"开始", Snackbar.LENGTH_LONG).show();
                                        isShowSignTime = false;
                                    }
                                }
                            }));
                        }
                    }
                }
            }));
        }else if (course.getSignStatus() ==2 && course.getSignOutStatus() != null && course.getSignOutStatus() == 2) {
            btnSign.setEnabled(false);
            btnSign.setText("已签退");
        }else{
            signBtnStatus();
        }
    }

    private void signBtnStatus() {
        if (course.getSignStatus() == 2) { // 已签到
            if (course.getSignType() != null && course.getSignType() == 1) {
                // 进行拍照签到
                if (course.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO) {
                    btnSign.setEnabled(true);
                    btnSign.setText("拍照签到");
                } else {
                    btnSign.setText(SignUtils.getSignStatus(course.getSignStatus()));
                    btnSign.setEnabled(false);
                }
            }else if (course.getSignOutStatus() == 2) { // 已签退
                btnSign.setEnabled(false);
                btnSign.setText("已签退");
            }
            backgroundGetWifiList();
            if (!wifiList.isEmpty()) {
                btnQrCodeSign.setText(R.string.generate_qr_code);
                btnQrCodeSign.setEnabled(true);
            }
        } else { // 未签到
            if (course.getSignStatus() == 1) { // 可以签到
                btnSign.setEnabled(true);
                btnSign.setText(getString(R.string.a_key_to_sign));

                btnQrCodeSign.setEnabled(true);
                btnQrCodeSign.setText(getString(R.string.qr_code_sign));
            } else { // 不可以签到
                // 早退状态签退
                if (course.getSignStatus() == 5 && course.getSignType() == 2) {
                    if (course.getSignOutStatus() == 1) {
                        btnSign.setEnabled(true);
                        btnSign.setText("签退");

                        btnQrCodeSign.setEnabled(true);
                        btnQrCodeSign.setText("扫码签退");
                    }else{
                        btnQrCodeSign.setEnabled(false);
                        btnQrCodeSign.setText("已签退");
                    }
                }else{
                    btnSign.setText(SignUtils.getSignStatus(course.getSignStatus()));
                    btnSign.setEnabled(false);
                }
            }
        }
    }

    private void initData() {
        wifiList.add(WifiUtil.connectionAddress());
        requestMembers();
        signId = course.getCourseSignId();
        tvTitle.setText(course.getName());
        tvClassRoom.setText(course.getRoomName());
        tvTeacherName.setText(getString(R.string.teacher_name, course.getTeacherName()));
        tvTime.setText(course.getActStartTime());
        tvJoinCode.setText(getString(R.string.join_code, course.getId()));
        userInfo = UserUtils.getUserInfo();
        if (userInfo == null) {
            ToastUtils.warning("用户信息异常,请重新登录");
            ActivityStackManager.finish();
        }
        startSign();

        scoringRank();
    }

    /**
     * 获取得分与排名
     */
    private void scoringRank() {
        if (userInfo == null) return;
        if (userInfo.getId() == null) return;
        addDisposable(CourseScoringService.getInstance().findCourseScoringRank(course.getCourseDetailId(),userInfo.getId()).subscribe(courseScoringRank -> {
            if (courseScoringRank != null && courseScoringView != null) {
                if (courseScoringRank.getScore() != null || courseScoringRank.getRank() != null) {
                    courseScoringView.setVisibility(View.VISIBLE);
                    courseScoringView.setScoringRanking(courseScoringRank.getRank());
                    courseScoringView.setCourseScore(courseScoringRank.getScore());
                }
            }
        }));

    }

    /**
     * 后台静默获取wifi列表 ， change generate qr code btn state
     */
    private void backgroundGetWifiList() {
        compositeDisposable.add(WifiUtil.getWifiList().subscribe(strings -> {
            if (strings == null || !strings.isEmpty()) {
                wifiList.addAll(strings);
                if (btnQrCodeSign != null) {
                    btnQrCodeSign.setText(R.string.generate_qr_code);
                    btnQrCodeSign.setEnabled(true);
                }
            }
        }));
    }

    private void setOnListener() {
        componentAdapter.setOnItemClickListener((adapter, view, position) -> {
            ComponentBean componentBean = (ComponentBean)adapter.getData().get(position);
            Intent intent = new Intent();
            switch (componentBean.getIconResId()) {
                case R.mipmap.ic_resources_share:
                    intent.setClass(CourseDetailActivity.this, SharedResourceActivity.class);
                    intent.putExtra(SharedResourceActivity.EXTRA_REL_ID, course.getId());
                    intent.putExtra(SharedResourceActivity.EXTRA_REL_TYPE, Constant.FLAG_REL_TYPE_COURSE);
                    intent.putExtra(SharedResourceActivity.EXTRA_TEACHER_ID, course.getTeacherId());
                    intent.putExtra(SharedResourceActivity.EXTRA_RESOURSE_TYPE, FileFunctionFlag.COURSE);
                    startActivity(intent);
                    break;
                case R.mipmap.ic_test:
                    intent.setClass(CourseDetailActivity.this, ExamActivity.class);
                    intent.putExtra(ExamActivity.EXTRA_REL_ID, String.valueOf(course.getId()));
                    intent.putExtra(ExamActivity.EXTRA_REL_TYPE, Constant.FLAG_REL_TYPE_COURSE);
                    startActivity(intent);
                    break;
                case R.mipmap.ic_question_answer:
                    StudentQAListActivity.Companion.navigation(CourseDetailActivity.this, String.valueOf(course.getId()), Constant.FLAG_REL_TYPE_COURSE);
                    break;
                case R.mipmap.ic_vote:
                    intent.setClass(CourseDetailActivity.this, VoteActivity.class);
                    intent.putExtra(VoteActivity.EXTRA_REL_ID, course.getId());
                    intent.putExtra(VoteActivity.EXTRA_TEACHER_ID, course.getTeacherId());
                    intent.putExtra(VoteActivity.EXTRA_REL_TYPE, Constant.FLAG_REL_TYPE_COURSE);
                    startActivity(intent);
                    break;
                case R.mipmap.ic_voice:
                    startVoice();
                    break;
                case R.mipmap.ic_seat:
                    requestStudentList();
                    break;
                case R.mipmap.ic_course_task:
                    CourseTaskActivity.navigation(CourseDetailActivity.this, String.valueOf(course.getId()));
                    break;
                case R.mipmap.ic_leave:
                    showLeaveDialog();
                    break;
                case R.mipmap.ic_discussion_group:
                    GroupsActivity.Companion.navigation(CourseDetailActivity.this,course.getCourseDetailId(),Constant.FLAG_REL_TYPE_COURSE);
                    break;
            }
        });

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                reqCourseDetail();
                scoringRank();
            }
        });

        courseScoringView.setOnClickListener(v -> CourseScoringRankingActivity.navigation(CourseDetailActivity.this, course));
    }


    @OnClick({
            R.id.btn_sign,
            R.id.btn_qr_code_sign,
            R.id.sign_failed_helper
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sign:
                isShowSignTime = true;
                if (course.getSignStatus() == 2 && course.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO) {
                    compositeDisposable.add(WebTimeHandle.checkSignStatus(course).subscribe((Consumer<Integer>) integer -> {
                        if (integer == 1) {
                            if (signId != -1) {
                                SignUtils.showTakePhotoDialog(CourseDetailActivity.this, takeSelfPhotoListener);
                            } else {
                                ToastUtils.info("数据异常，当前无法拍照签到");
                            }
                        }else{
                            Snackbar.make(getWindow().getDecorView(), "当前不在签到时间，无法进行拍照签到", Snackbar.LENGTH_LONG).show();
                        }
                    }));
                } else {
                    startSign();
                }
                break;
            case R.id.btn_qr_code_sign:
                if (course.getSignStatus() == 2) {
                    if (!wifiList.isEmpty()) {
                        Intent generateQrCodeIntent = new Intent();
                        generateQrCodeIntent.setClass(CourseDetailActivity.this, GenerateQRCodeActivity.class);
                        generateQrCodeIntent.putExtra(GenerateQRCodeActivity.EXTRA_COURSE_TITLE, course.getName() + "二维码");
                        generateQrCodeIntent.putExtra(GenerateQRCodeActivity.EXTRA_SIGN_WIFI, course.getMck());
                        startActivity(generateQrCodeIntent);
                    } else {
                        Snackbar.make(getWindow().getDecorView(), "未获取到WIFI列表信息，无法生成二维码",  Snackbar.LENGTH_LONG).show();
                    }

                } else {
                    showQRCodeDialog();
                }
                break;
            case R.id.sign_failed_helper:
                CourseSignFailedHelperActivity.Companion.navigation(this);
                break;
        }
    }

    private void showLeaveDialog() {
        final CreateLeaveDialog createLeaveDialog = CreateLeaveDialog.Companion.newInstance();
        createLeaveDialog.show(getSupportFragmentManager(), "create_leave");
        createLeaveDialog.setAddImageClickListener(view -> addDisposable(PermissionUtil.checkCameraPermission(CourseDetailActivity.this).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    ImageUtil.captureImageByCamera(CourseDetailActivity.this, LEAVE_IMG_REQUEST_CODE);
                    leaveImageView = view;
                }
            }
        })));
        createLeaveDialog.setSubmitListener(leaveInfo -> {
            if (!TextUtils.isEmpty(leaveInfo.getReason())) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("detailId", course.getCourseDetailId());
                params.put("reason", leaveInfo.getReason());
                if (leaveImageId != -1) {
                    params.put("resourceId", leaveImageId);
                }
                leaveCall = userApi.leave(params);
                leaveCall.enqueue(new ServerCallback<Integer>() {
                    @Override
                    public void onResponse(boolean success, ServerResponse<Integer> response) {
                        if (success) {
                            ToastUtils.success("提交成功");
                        }
                    }
                });
                if (createLeaveDialog.getDialog().isShowing()) {
                    createLeaveDialog.dismiss();
                }
            }else{
                ToastUtils.info("请输入请假原因");
            }
        });

        createLeaveDialog.setLeaveImageLongClickListener(view -> {
            if (view.getTag() != null) {
                try{
                    if (leaveImageId != -1) {
                        ShowBigImageActivity.navigation(CourseDetailActivity.this, leaveImageId);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.info(R.string.data_incorrect);
                }
            }
        });
    }

    private void showQRCodeDialog() {
        final android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setTitle("二维码签到");
        builder.setItems(new String[]{"扫描二维码", "生成二维码"}, (dialog, which) -> {
            Intent intent = new Intent();
            switch (which) {
                case 0:
                    intent.setClass(CourseDetailActivity.this, CaptureActivity.class);
                    intent.putExtra("autoEnlarged", true);
                    startActivityForResult(intent, SCAN_WIFI_QR_CODE_REQUEST_CODE);
                    break;
                case 1:
                    if (wifiList.size() > 0) {
                        intent.setClass(CourseDetailActivity.this, GenerateQRCodeActivity.class);
                        intent.putExtra(GenerateQRCodeActivity.EXTRA_SIGN_WIFI, course.getMck());
                        intent.putExtra(GenerateQRCodeActivity.EXTRA_COURSE_TITLE, course.getName() + "二维码");
                        startActivity(intent);
                    } else {
                        ToastUtils.warning("未获取到wifi信息，请选择<扫描二维码>扫描二维码签到");
                    }

                    break;
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 抢答
     */
    @SuppressLint("CheckResult")
    private void startVoice() {
        final PermissionUtil.Build build = new PermissionUtil.Build();
        build.setPermissions(new String[]{Permission.RECORD_AUDIO});
        build.setTips("请允许使用录音权限，方便您进行抢答");
        compositeDisposable.add(PermissionUtil.checkPermission(CourseDetailActivity.this, build).subscribe(voiceConsumer));
    }

    private Consumer voiceConsumer = new Consumer<PermissionUtil.PermissionResult>() {
        @SuppressLint("CheckResult")
        @Override
        public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
            if (permissionResult.isHasAccess()) {
                vieAnswerQuery();
            }else{
                final PermissionUtil.Build build = new PermissionUtil.Build();
                build.setPermissions(new String[]{Permission.RECORD_AUDIO});
                build.setTips("请允许使用录音权限，方便您进行抢答");
                compositeDisposable.add(PermissionUtil.checkPermission(CourseDetailActivity.this, build).subscribe(voiceConsumer));
            }
        }
    };

    private void vieAnswerQuery() {
        final VieAnswer vieAnswer = new VieAnswer(Constant.FLAG_REL_TYPE_COURSE, course.getCourseDetailId());
        goIntoCall = vieAnswerApi.goInto(vieAnswer);
        goIntoCall.enqueue(new ServerCallback<Void>(this,"正在抢答中...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    long imId = course.getTeacherId();
                    VieAnswerBean vieAnswerBean = new VieAnswerBean(Constant.FLAG_REL_TYPE_COURSE, course.getId(), course.getCourseDetailId(), imId, course.getTeacherName(),false);
                    VieAnswerActivity.Companion.navigation(CourseDetailActivity.this, vieAnswerBean);
                }
            }
        });

    }

    /**
     * 设置互动组件
     */
    private void setInteractive() {
        componentAdapter = new InteractiveAdapter(CourseInteractiveData.getCreateData());
        gvCourseInteractive.setLayoutManager(new GridLayoutManager(this,3));
        gvCourseInteractive.addItemDecoration(ItemDecorationUtil.horizontalDividerItemDecoration(this, AndroidUtils.dp2px(20)));
        gvCourseInteractive.setAdapter(componentAdapter);
    }


    /**
     * get wifi list
     */
    @SuppressLint("CheckResult")
    private void checkWifiPermission() {
        final PermissionUtil.Build build = new PermissionUtil.Build();
        build.setPermissions(Constant.SIGN_PERMISSION_GROUP);
        build.setTips(getResources().getString(R.string.request_wifi_permission_tips));
        compositeDisposable.add(PermissionUtil.checkPermission(this, build).subscribe(permissionResult -> {
            if (permissionResult.isHasAccess()) { // 有权限
                if (WifiUtil.checkMacAddress(course.getMck(),wifiList)) {
                    if (course.getSignType() != null) {
                        String title = course.getSignType() == 1 ? "正在签到..." : "正在签退...";
                        signHandle(title, course.getSignType());
                    }
                }else{
                    ToastUtils.warning("未扫描到校园WIFI信号");
                }
//                addDisposable(WifiUtil.getWifiList().map(isSignFunc).map(notWifiListTips).subscribe(isSignHandleConsumer));
            }else{
                NotPermissionTipsDialog.Companion.newInstance().show(getSupportFragmentManager(), "not_permission"+ SystemClock.currentThreadTimeMillis());
            }
        }));
    }

    private void validateMacAddress() {
        compositeDisposable.add(WifiUtil.getWifiList().map(isSignFunc).map(checkPermissionFunc).subscribe(isSignHandleConsumer));
    }

    /**
     * 检查权限
     */
    private Function checkPermissionFunc = (Function<Boolean, Boolean>) aBoolean -> {
        if (aBoolean) {
            return true;
        }else{
            checkWifiPermission();
            return false;
        }
    };

    /**
     * 没有权限提示
     */
    private Function notWifiListTips = (Function<Boolean, Boolean>) aBoolean -> {
        if (aBoolean) {
            return true;
        }else {
            if (!CourseDetailActivity.this.isFinishing() && !isSaveInstanceState) {
                NotPermissionTipsDialog.Companion.newInstance().show(getSupportFragmentManager(), "not_permission"+ SystemClock.currentThreadTimeMillis());
            }
            return false;
        }
    };


    /**
     * 判断是否可以签到
     */
    private Function isSignFunc = new Function<List<String>, Boolean>() {
        @Override
        public Boolean apply(List<String> wifis) throws Exception {
            if (wifis != null && !wifis.isEmpty()) { // 有wifi , 缓存列表
                wifiList.addAll( wifis);
                App.getInstance().getAcache().put(WifiUtil.COURSE_WIFI_CACHE_KEY, WifiUtil.wifiListJson(wifiList), WifiUtil.WIFI_CACHE_EXPIRED_TIME);
                return WifiUtil.checkMacAddress(course.getMck(),wifiList);
            } else { // 没有wifi列表 ， 取缓存列表
                final String wifiListJsonStr = App.getInstance().getAcache().getAsString(WifiUtil.COURSE_WIFI_CACHE_KEY);
                if (!TextUtils.isEmpty(wifiListJsonStr)) {
                    wifis = WifiUtil.wifiList(wifiListJsonStr);
                    if (wifis != null) {
                        wifiList.addAll(wifis);
                        if (wifiList.isEmpty()) {
                            showNotFoundWifiListDialog();
                        }else{
                            return WifiUtil.checkMacAddress(course.getMck(),wifiList);
                        }
                    }else{
                        return WifiUtil.checkMacAddress(course.getMck(),wifiList);
                    }
                }else{
                    return WifiUtil.checkMacAddress(course.getMck(),wifiList);
                }
            }
            return WifiUtil.checkMacAddress(course.getMck(),wifiList);
        }
    };

    /**
     * 验证
     */
    private Consumer isSignHandleConsumer = new Consumer<Boolean>() {
        @Override
        public void accept(Boolean aBoolean) throws Exception {
            if (aBoolean) { // mac 地址验证通过 ，这时需要请求网络上传数据
                if (course.getSignType() != null) {
                    String title = course.getSignType() == 1 ? "正在签到..." : "正在签退...";
                    signHandle(title, course.getSignType());
                }
            }
        }
    };

    /**
     * 未获取到wifi列表提示dialog
     */
    private void showNotFoundWifiListDialog() {
        SpannableStringBuilder notFountWIFIListTips = SignUtils.getNotFountWifiListTips(this, permissionGuideListener);
        if (notFountWIFIListTips != null) {
            appCompatDialog = DialogUtils.getAppCompatDialog(this, R.layout.dialog_permission_prompt);
            TextView tips = (TextView) appCompatDialog.findViewById(R.id.tv_permission_tips);
            tips.setText(notFountWIFIListTips);
            tips.setMovementMethod(LinkMovementMethod.getInstance());
            appCompatDialog.findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (appCompatDialog != null && appCompatDialog.isShowing()) {
                        appCompatDialog.dismiss();
                    }
                }
            });
        }
    }

    /**
     * 开启wifi,位置信息详细引导
     */
    private View.OnClickListener permissionGuideListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (appCompatDialog != null) {
                appCompatDialog.dismiss();
            }
            startActivity(new Intent(CourseDetailActivity.this, PermissionGuideHelperActivity.class));
        }
    };


    private void signHandle(String title, final int signleType) {
        btnSign.setText(title);
        btnSign.setEnabled(false);
        final CourseSign courseSign = new CourseSign();
        courseSign.setUserId(userInfo.getId());
        courseSign.setCourseDetailId(course.getCourseDetailId());
        courseSign.setMck(AndroidUtils.getMobileOnlyFlag(this));
        if (signleType == 1) {
            courseSign.setStatus(2);
        }
        courseSign.setReason("");
        courseSign.setSignTh(signleType);
        Logger.d("签到-" + courseSign.toString());
        signCall = courseApi.sign(courseSign);
        signCall.enqueue(new ServerCallback<SignResult>(this, "正在签到...") {
            @Override
            public void onResponse(boolean success, ServerResponse<SignResult> response) {
                if (success) {
                    SignResult signResult = response.getBody();
                    signId = signResult.getId();
                    if (signleType == 2) {
                        course.setSignOutStatus(2);
                    }
                    course.setSignStatus(signResult.getStatus());
                    if (btnSign != null && course.getSignWay() == SignUtils.SIGN_WAY_TYPE_WIFI_PHOTO) {
                        if (signId != -1) {
                            SignUtils.showTakePhotoDialog(CourseDetailActivity.this, takeSelfPhotoListener);
                        } else {
                            ToastUtils.info("数据异常，当前无法拍照签到");
                        }
                        btnSign.setEnabled(true);
                    } else if (btnSign != null) {
                        btnSign.setEnabled(false);
                    }
                    showSignSuccess();
                    signBtnStatus();

                    final UpdateCourseEvent updateCourseEvent = new UpdateCourseEvent();
                    updateCourseEvent.setCourse(course);
                    EventBus.getDefault().post(updateCourseEvent);
                } else {
                    if (btnSign != null) {
                        btnSign.setEnabled(true);
                        btnSign.setText(getString(R.string.a_key_to_sign));
                    }
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<SignResult>> call, Throwable t) {
                super.onFailure(call, t);
                if (btnSign != null) {
                    btnSign.setEnabled(true);
                    btnSign.setText(getString(R.string.a_key_to_sign));
                }
            }
        });
    }

    /**
     * 多次图片签到上传
     */
    @SuppressLint("CheckResult")
    private void photoSign() {
        checkWebTimeSignStatus().subscribe(integer -> {
            if (integer == 1 && course.getSignStatus() == 2) {
                if (PermissionUtil.hasPermission(PermissionGroup.CAMERA_AND_STORE)) {
                    ImageUtil.captureImageByCamera(CourseDetailActivity.this, TAKE_SELF_PHOTO_REQUEST_CODE);
                }else{
                    final PermissionUtil.Build build = new PermissionUtil.Build();
                    build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                    build.setTips("请允许我们访问拍照和存储权限，以方便您进行拍照签到");
                    compositeDisposable.add(PermissionUtil.checkPermission(CourseDetailActivity.this, build).subscribe(cameraConsumer));
                }

            }
        });
    }

    private Consumer cameraConsumer = new Consumer<PermissionUtil.PermissionResult>() {
        @SuppressLint("CheckResult")
        @Override
        public void accept(PermissionUtil.PermissionResult permissionResult) throws Exception {
            if (permissionResult.isHasAccess()) { // 允许拍照
                ImageUtil.captureImageByCamera(CourseDetailActivity.this, TAKE_SELF_PHOTO_REQUEST_CODE);
            }else{ // 未获取到拍照权限
                final PermissionUtil.Build build = new PermissionUtil.Build();
                build.setPermissions(PermissionGroup.CAMERA_AND_STORE);
                build.setTips("请允许我们访问拍照和存储权限，以方便您进行拍照签到");
                compositeDisposable.add(PermissionUtil.checkPermission(CourseDetailActivity.this, build).subscribe(cameraConsumer));
            }
        }
    };

    /**
     * 拍摄本人照片
     */
    private View.OnClickListener takeSelfPhotoListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            photoSign();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SCAN_WIFI_QR_CODE_REQUEST_CODE == requestCode) { // 扫描二维码
            if (null != data) {
                Bundle extras = data.getExtras();
                if (null == extras) {
                    ToastUtils.warning("未获取到解析的内容");
                    return;
                }
                String result = data.getStringExtra("result");
                if (!TextUtils.isEmpty(result)) {
                    paserQRCodeResult(result);
                } else {
                    ToastUtils.info("二维码数据为空");
                }
            }
        } else if (TAKE_SELF_PHOTO_REQUEST_CODE == requestCode) { // 拍摄个人照片
            if (resultCode != RESULT_CANCELED) {
                final File captureImageFile = ImageUtil.getCaptureImageFile();
                if (captureImageFile != null) {
                    compressFile(captureImageFile,TAKE_SELF_PHOTO_REQUEST_CODE);
                }
            }
        }else if (LEAVE_IMG_REQUEST_CODE == requestCode){
            if (resultCode != RESULT_CANCELED) {
                final File captureImageFile = ImageUtil.getCaptureImageFile();
                if (captureImageFile != null) {
                    compressFile(captureImageFile,LEAVE_IMG_REQUEST_CODE);
                }
            }
        }
    }

    /**
     * 压缩文件
     *
     * @param captureImageFile
     */
    @SuppressLint("CheckResult")
    private void compressFile(File captureImageFile,int reqCode) {
        progressDialog = new ProgressDialog(CourseDetailActivity.this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在上传...");
        progressDialog.show();
        if (captureImageFile != null) {
            if (reqCode == TAKE_SELF_PHOTO_REQUEST_CODE) {
                Disposable disposable = ImageUtil.ImageWaterMarkTask(CourseDetailActivity.this, captureImageFile).subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        if (file != null) {
                            uploadPhoto(file, progressDialog);
                        }
                    }
                });
                compositeDisposable.add(disposable);
            }else if (reqCode == LEAVE_IMG_REQUEST_CODE) {
                Disposable disposable = Observable.just(captureImageFile).map(file -> {
                    final List<File> files = Luban.with(CourseDetailActivity.this).load(file).get();
                    if (files != null && files.size() > 0) {
                        return files.get(0);
                    } else {
                        return file;
                    }
                }).subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        uploadLeaveImage(file, progressDialog);
                    }
                });
                compositeDisposable.add(disposable);
            }
        }
    }

    private void uploadLeaveImage(File file, final ProgressDialog progressDialog) {
        if (UserUtils.getUserInfo() != null) {
            if (file != null) {
                String fileExtension = FilenameUtils.getExtension(file.getPath());
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", file.getName(), requestBody);
                uploadCall = resourceApi.uploadTemp(filePart);
                uploadCall.enqueue(new ServerCallback<List<Integer>>() {
                    @Override
                    public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                        if (success) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            ToastUtils.success("上传成功");
                            if (!response.getBody().isEmpty()) {
                                Integer imageId = response.getBody().get(0);
                                if (leaveImageView != null) {
                                    leaveImageId = imageId;
                                    if (imageId != null) {
                                        withGlide().load(new GlideUrlModel(ApiConstantKt.getRemoteImageUrl()+imageId)).into(leaveImageView);
                                    }
                                }
                            }
                        }
                    }
                });
            }
        } else {
            ToastUtils.warning("帐号异常，请重新登录之后重试");
        }
    }

    /**
     * 上传图片
     *
     * @param file
     * @param progressDialog
     */
    private void uploadPhoto(File file, final ProgressDialog progressDialog) {
        if (UserUtils.getUserInfo() != null) {
            if (file != null) {
                String fileExtension = FilenameUtils.getExtension(file.getPath());
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", file.getName(), requestBody);
                uploadCall = resourceApi.upload(filePart,
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileUtil.getFileType(fileExtension))),
                        RequestBody.create(MediaType.parse("text/plain"), file.getName()),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileFunctionFlag.COURSE_PHOTO_SIGN)),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(signId)),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Boolean.FALSE)));
                uploadCall.enqueue(new ServerCallback<List<Integer>>() {
                    @Override
                    public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                        if (success) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            ToastUtils.success("上传成功");
                        }
                    }
                });
            }
        } else {
            ToastUtils.warning("帐号异常，请重新登录之后重试");
        }
    }

    /**
     * 解析扫描的二维码数据
     *
     * @param result
     */
    private void paserQRCodeResult(String result) {
        try {
            final Gson gson = new Gson();
            SignQrCodeContent signQrCodeContent = gson.fromJson(result, SignQrCodeContent.class);
            String checkCode = signQrCodeContent.getDate() + "dayaokeji";
            final String md5CheckCode = MD5Util.md5(checkCode);
            if (ObjectUtils.equals(md5CheckCode, signQrCodeContent.getCheckcode().toUpperCase())) {
                if (SignUtils.isExpiredTime(signQrCodeContent.getDate())) {
                    wifiList.addAll(signQrCodeContent.getLoc_array());
                    if (WifiUtil.checkMacAddress(course.getMck(),wifiList)) {
                        if (course.getSignType() != null) {
                            String title = course.getSignType() == 1 ? "正在签到..." : "正在签退...";
                            signHandle(title, course.getSignType());
                        }
                    }
                }
            } else {
                ToastUtils.warning("二维码数据无效");
            }

        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.error("二维码结果解析失败");
        }
    }

    private void requestMembers() {
        studentListCall = courseApi.member(course.getCourseDetailId());
        studentListCall.enqueue(new ServerCallback<List<Member>>(this,"正在获用户信息...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Member>> response) {
                if (success) {
                    List<Member> memberList = response.getBody();
                    courseMembersAvatarAdapter.setNewData(memberList);
                    for (Member member : memberList) {
                        saveUserInfo(member);
                    }
                    if (tvMembersCount != null) {
                        tvMembersCount.setText(String.valueOf(memberList.size()));
                    }
                    courseMembersAvatarAdapter.getData();
                }
            }
        });
    }

    private void requestStudentList() {
        studentListCall = courseApi.member(course.getCourseDetailId());
        studentListCall.enqueue(new ServerCallback<List<Member>>(this,"正在获用户信息...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Member>> response) {
                if (success) {
                    List<Member> memberList = response.getBody();
                    for (Member member : memberList) {
                        saveUserInfo(member);
                        if (userInfo != null) {
                            if (ObjectUtils.equals(String.valueOf(member.getUserId()), userInfo.getId())) {
                                CourseDetailActivity.member = member;
                                if (!isFinishing()) {
                                    Intent intent = new Intent();
                                    intent.setClass(CourseDetailActivity.this, StudentSeatActivity.class);
                                    intent.putExtra(StudentSeatActivity.EXTRA_COURSE_DETAIL_ID, course.getCourseDetailId());
                                    intent.putExtra(StudentSeatActivity.EXTRA_COURSE_ID, course.getId());
                                    intent.putExtra(StudentSeatActivity.EXTRA_ROOM_ID, course.getRoomId());
                                    intent.putExtra(StudentSeatActivity.EXTRA_MEMBER, member);
                                    startActivity(intent);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private void saveUserInfo(final Member member) {
        try {
            final UserInfo userInfo = new UserInfo();
            userInfo.setWorkNo(member.getWorkNo());
            if (UserUtils.getUserInfo() != null) {
                userInfo.setUniversityId(UserUtils.getUserInfo().getUniversityId());
            }else{
                userInfo.setUniversityId(0L);
            }
            userInfo.setName(member.getName());
            UserInfoDao.saveUserInfo(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Subscribe
    public void updateSeat(UpdateCourseEvent updateCourseEvent) {
        String userSeat = updateCourseEvent.getUserSeat();
        if (!TextUtils.isEmpty(userSeat)) {
            member.setSeat(userSeat);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void finishCourseDetail(DeleteCourseFinishEvent deleteCourseFinishEvent) {
        ActivityStackManager.finish(CourseDetailActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        isSaveInstanceState = true;
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (signCall != null) {
            signCall.cancel();
        }
        if (studentListCall != null) {
            studentListCall.cancel();
        }
        compositeDisposable.clear();
        if (goIntoCall != null) {
            goIntoCall.cancel();
        }
        if (leaveCall != null) {
            leaveCall.cancel();
        }
        if (courseDetailCall != null) {
            courseDetailCall.cancel();
        }
        super.onDestroy();
    }
}
